/**
 * handle gateway manager page logic.
 */
var __gatewayId = null;
function onLoadGateway(gateway) {
	$('#textinput-devId').val(gateway.devId);
	$('#textinput-name').val(gateway.name);
	$('#textinput-description').val(gateway.description);
	$('#textinput-panid').val(gateway.panId);
	$('#textinput-account').val(gateway.account);
	$('#textinput-logintime').val(gateway.logintime);

	$('#controllerPage').attr('href', "/getControllers?gwId="+gateway.devId);
	$('#groupPage').attr('href', "/getGroups?gwId="+gateway.devId);
	
	$('#groupsInfo').text("Group count:" + gateway.groupCount);
	$('#controllersInfo').text("Controller count:" + gateway.controllerCount);	
}

function loadGateway(gwId) {
    $.ajax({
        url : ('/loadGateway?gid='+gwId),
        type : 'GET',
        dataType : 'json',
        success : function(result) {
            if (result.err) {
                showMsgPopup('load controller info failed:' + result.err);
            } else {
                onLoadGateway(result.gateway);
            }
        },
        error : function(_, status, e) {
            showMsgPopup('load controller failed:' + e);
        }
    });
}

function pageinit() {
	$('#lvGateways').find('.gatewayName').each(function(i, a) {
		var input = $(a).find("input").first();
		var gatewayId = input.val();
		$(a).off('click').on('click', function(event) {
			__gatewayId = gatewayId;
			$("#gatewayName").text("Gateway: " + __gatewayId);
			loadGateway(__gatewayId);
			event.preventDefault();
		});
	});
	
	$('#editGateway').off('click').on('click', function(event) {
		if (__gatewayId == null) {
			showMsgPopup("Please select a gateway to edit");
			return;
		}
		
		$.mobile.changePage("/editGateway?gwId=" + __gatewayId, {
			transition : "flip",
			role : "dialog"
		});
		event.preventDefault();
	});
}

$(document).on('pageinit', function() {
	pageinit();
});
